package com.yc.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.DTO.TestAnswerDTO;
import com.yc.bean.*;
import com.yc.dao.*;
import com.yc.utils.TestScoringUtil;
import com.yc.web.controller.model.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yc.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Value;
import java.io.InputStream;
import java.util.UUID;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.math.BigDecimal;

@Service
@Slf4j
@Transactional
public class TestServiceImpl implements TestService {

    @Autowired
    private TestCategoryDao testCategoryDao;
    
    @Autowired
    private PsychologicalTestDao psychologicalTestDao;
    
    @Autowired
    private TestQuestionDao testQuestionDao;
    
    @Autowired
    private TestOptionDao testOptionDao;
    
    @Autowired
    private UserTestRecordDao userTestRecordDao;
    
    @Autowired
    private UserTestAnswerDao userTestAnswerDao;
    
    @Autowired
    private TestResultDao testResultDao;
    
    @Autowired
    private TestScoreLevelDao testScoreLevelDao;
    
    @Autowired
    private OSSService ossService;
    
    @Value("${app.domain:http://localhost:5173}")
    private String appDomain;
    
    @Value("${app.backend.domain:http://localhost:8088}")
    private String backendDomain;

    @Override
    public ResponseResult getCategories() {
        try {
            List<TestCategory> categories = testCategoryDao.selectList(
                new QueryWrapper<TestCategory>()
                    .eq("status", 1)
                    .orderByAsc("sortOrder")
            );
            return ResponseResult.ok("获取成功").setData(categories);
        } catch (Exception e) {
            log.error("获取测评分类失败", e);
            return ResponseResult.error("获取分类失败");
        }
    }

    @Override
    public ResponseResult getTestList(Long userId, String categoryId, String status, Integer page, Integer size) {
        try {
            Page<PsychologicalTest> pageObj = new Page<>(page, size);
            
            QueryWrapper<PsychologicalTest> wrapper = new QueryWrapper<>();
            wrapper.eq("status", 1);
            
            if (categoryId != null && !categoryId.isEmpty()) {
                wrapper.eq("categoryId", categoryId);
            }
            
            IPage<PsychologicalTest> result = psychologicalTestDao.selectPage(pageObj, wrapper);
            
            // 如果提供了userId，查询用户的测评状态
            if (userId != null) {
                List<PsychologicalTest> tests = result.getRecords();
                for (PsychologicalTest test : tests) {
                    UserTestRecord record = userTestRecordDao.selectLatestRecord(userId, test.getTestId());
                    if (record != null) {
                        test.setUserStatus(convertStatusToInteger(record.getStatus()));
                        test.setLastTestTime(record.getSubmitTime() != null ? record.getSubmitTime() : record.getUpdateTime());
                    } else {
                        test.setUserStatus(0); // 未开始
                    }
                }
            }
            
            return ResponseResult.ok("获取成功").setData(result);
        } catch (Exception e) {
            log.error("获取测评列表失败", e);
            return ResponseResult.error("获取测评列表失败");
        }
    }

    @Override
    public ResponseResult getTestDetail(Long testId, Long userId) {
        try {
            // 获取测评信息
            PsychologicalTest test = psychologicalTestDao.selectById(testId);
            if (test == null) {
                return ResponseResult.error("测评不存在");
            }
            
            // 获取题目和选项
            List<TestQuestion> questions = testQuestionDao.selectByTestId(testId);
            for (TestQuestion question : questions) {
                List<TestOption> options = testOptionDao.selectByQuestionId(question.getQuestionId());
                question.setOptions(options);
            }
            test.setQuestions(questions);
            
            // 如果用户已登录，检查测评状态
            if (userId != null) {
                UserTestRecord record = userTestRecordDao.selectLatestRecord(userId, testId);
                if (record != null) {
                    // 将字符串状态转换为整数状态
                    test.setUserStatus(convertStatusToInteger(record.getStatus()));
                    test.setRecordId(record.getRecordId());
                    
                    // 计算进度百分比
                    if (record.getCurrentQuestionIndex() != null && questions.size() > 0) {
                        int progress = (int) Math.round((double) record.getCurrentQuestionIndex() / questions.size() * 100);
                        test.setProgress(Math.min(progress, 100)); // 确保不超过100%
                    } else {
                        test.setProgress(0);
                    }
                    
                    // 如果测评进行中，返回已答题目
                    if ("in_progress".equals(record.getStatus())) {
                        List<UserTestAnswer> answers = userTestAnswerDao.selectByRecordId(record.getRecordId());
                        test.setUserAnswers(answers);
                    }
                } else {
                    test.setUserStatus(0); // 0-未开始
                    test.setProgress(0);
                }
            }
            
            return ResponseResult.ok().setData(test);
        } catch (Exception e) {
            log.error("获取测评详情失败", e);
            return ResponseResult.error("获取测评详情失败");
        }
    }

    @Override
    public ResponseResult startTest(Long testId, Long userId) {
        try {
            // 检查是否存在进行中的测评
            UserTestRecord existingRecord = userTestRecordDao.selectLatestRecord(userId, testId);
            if (existingRecord != null && "in_progress".equals(existingRecord.getStatus())) {
                return ResponseResult.ok("继续进行中的测评").setData(existingRecord.getRecordId());
            }
            
            // 创建新的测评记录
            UserTestRecord record = new UserTestRecord();
            record.setUserId(userId);
            record.setTestId(testId);
            record.setStatus("in_progress"); // 进行中
            record.setCurrentQuestionIndex(0); // 初始化为0
            record.setStartTime(LocalDateTime.now());
            record.setCreateTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            
            userTestRecordDao.insert(record);
            
            return ResponseResult.ok("测评开始成功").setData(record.getRecordId());
        } catch (Exception e) {
            log.error("开始测评失败", e);
            return ResponseResult.error("开始测评失败");
        }
    }

    @Override
    public ResponseResult saveProgress(TestAnswerDTO answerDTO) {
        try {
            // 获取测评记录
            UserTestRecord record = userTestRecordDao.selectById(answerDTO.getRecordId());
            if (record == null) {
                return ResponseResult.error("测评记录不存在");
            }
            
            if (!"in_progress".equals(record.getStatus())) {
                return ResponseResult.error("测评已结束，无法继续答题");
            }
            
            // 获取题目和选项信息
            List<TestQuestion> questions = testQuestionDao.selectByTestId(record.getTestId());
            TestQuestion question = questions.get(answerDTO.getQuestionIndex());
            List<TestOption> options = testOptionDao.selectByQuestionId(question.getQuestionId());
            TestOption selectedOption = options.get(answerDTO.getSelectedAnswer());
            
            // 检查是否已经回答过这道题
            QueryWrapper<UserTestAnswer> wrapper = new QueryWrapper<>();
            wrapper.eq("recordId", answerDTO.getRecordId())
                   .eq("questionIndex", answerDTO.getQuestionIndex());
            UserTestAnswer existingAnswer = userTestAnswerDao.selectOne(wrapper);
            
            if (existingAnswer != null) {
                // 更新答案
                existingAnswer.setSelectedOptionId(selectedOption.getOptionId());
                existingAnswer.setOptionValue(selectedOption.getOptionValue());
                userTestAnswerDao.updateById(existingAnswer);
            } else {
                // 新增答案
                UserTestAnswer answer = new UserTestAnswer();
                answer.setRecordId(answerDTO.getRecordId());
                answer.setQuestionId(question.getQuestionId());
                answer.setQuestionIndex(answerDTO.getQuestionIndex());
                answer.setSelectedOptionId(selectedOption.getOptionId());
                answer.setOptionValue(selectedOption.getOptionValue());
                answer.setAnswerTime(LocalDateTime.now());
                userTestAnswerDao.insert(answer);
            }
            
            // 更新进度
            int totalQuestions = questions.size();
            int answeredQuestions = userTestAnswerDao.selectCount(
                new QueryWrapper<UserTestAnswer>().eq("recordId", answerDTO.getRecordId())
            ).intValue();
            
            int progress = (int) Math.round((double) answeredQuestions / totalQuestions * 100);
            record.setCurrentQuestionIndex(answeredQuestions); // 设置当前题目索引
            record.setUpdateTime(LocalDateTime.now());
            userTestRecordDao.updateById(record);
            
            return ResponseResult.ok("保存成功");
        } catch (Exception e) {
            log.error("保存答题进度失败", e);
            return ResponseResult.error("保存失败");
        }
    }

    @Override
    public ResponseResult submitTest(TestAnswerDTO answerDTO) {
        try {
            // 获取测评记录
            UserTestRecord record = userTestRecordDao.selectById(answerDTO.getRecordId());
            if (record == null) {
                return ResponseResult.error("测评记录不存在");
            }
            
            // 批量保存所有答案
            if (answerDTO.getAnswers() != null && !answerDTO.getAnswers().isEmpty()) {
                List<TestQuestion> questions = testQuestionDao.selectByTestId(record.getTestId());
                
                for (int i = 0; i < answerDTO.getAnswers().size(); i++) {
                    Integer selectedAnswer = answerDTO.getAnswers().get(i);
                    if (selectedAnswer != null) {
                        TestQuestion question = questions.get(i);
                        List<TestOption> options = testOptionDao.selectByQuestionId(question.getQuestionId());
                        TestOption selectedOption = options.get(selectedAnswer);
                        
                        // 检查是否已存在答案
                        QueryWrapper<UserTestAnswer> wrapper = new QueryWrapper<>();
                        wrapper.eq("recordId", answerDTO.getRecordId())
                               .eq("questionIndex", i);
                        UserTestAnswer existingAnswer = userTestAnswerDao.selectOne(wrapper);
                        
                        if (existingAnswer != null) {
                            existingAnswer.setSelectedOptionId(selectedOption.getOptionId());
                            existingAnswer.setOptionValue(selectedOption.getOptionValue());
                            userTestAnswerDao.updateById(existingAnswer);
                        } else {
                            UserTestAnswer answer = new UserTestAnswer();
                            answer.setRecordId(answerDTO.getRecordId());
                            answer.setQuestionId(question.getQuestionId());
                            answer.setQuestionIndex(i);
                            answer.setSelectedOptionId(selectedOption.getOptionId());
                            answer.setOptionValue(selectedOption.getOptionValue());
                            answer.setAnswerTime(LocalDateTime.now());
                            userTestAnswerDao.insert(answer);
                        }
                    }
                }
            }
            
            // 计算总分和生成结果
            List<UserTestAnswer> answers = userTestAnswerDao.selectByRecordId(answerDTO.getRecordId());
            List<TestQuestion> questions = testQuestionDao.selectByTestId(record.getTestId());
            
            // 使用工具类计算总分（考虑反向计分）
            int totalScore = TestScoringUtil.calculateTotalScore(answers, questions);
            
            // 获取测评信息
            PsychologicalTest test = psychologicalTestDao.selectById(record.getTestId());
            String testType = test != null ? test.getType() : "general";
            
            // 从数据库获取评分标准，而不是使用硬编码逻辑
            TestScoreLevel scoreLevel = testScoreLevelDao.selectByTestIdAndScore(record.getTestId(), totalScore);
            
            String resultLevel;
            String resultDescription;
            String suggestions;
            
            if (scoreLevel != null) {
                // 使用数据库中的评分标准
                resultLevel = scoreLevel.getLevelName();
                resultDescription = scoreLevel.getDescription();
                suggestions = validateAndFixSuggestions(scoreLevel.getSuggestions());
                log.debug("从数据库获取并验证后的suggestions: {}", suggestions);
            } else {
                // 如果数据库中没有配置，则使用默认逻辑作为备选
                log.warn("未找到测评ID {} 分数 {} 对应的评分标准，使用默认逻辑", record.getTestId(), totalScore);
                resultLevel = TestScoringUtil.determineLevel(totalScore, testType);
                resultDescription = TestScoringUtil.generateSuggestions(resultLevel, totalScore, testType);
                suggestions = validateAndFixSuggestions(resultDescription);
            }
            
            // 更新测评记录状态
            record.setStatus("completed"); // 已完成
            record.setCurrentQuestionIndex(questions.size()); // 设置为总题目数表示完成
            record.setTotalScore(BigDecimal.valueOf(totalScore));
            record.setSubmitTime(LocalDateTime.now());
            record.setUpdateTime(LocalDateTime.now());
            userTestRecordDao.updateById(record);
            
            // 保存测评结果
            TestResult result = new TestResult();
            result.setRecordId(answerDTO.getRecordId());
            result.setUserId(record.getUserId());
            result.setTestId(record.getTestId());
            result.setTotalScore(BigDecimal.valueOf(totalScore));
            
            // 计算标准分（可以根据需要实现具体的标准化算法）
            BigDecimal standardScore = calculateStandardScore(totalScore, testType);
            result.setStandardScore(standardScore);
            
            result.setScoreLevel(resultLevel);
            result.setScoreDescription(resultDescription);
            
            // 可以根据需要设置维度分析、建议等字段
            result.setDimensions(generateDimensions(answers, testType));
            result.setSuggestions(suggestions); // 使用数据库中的建议
            result.setActionPlan(generateActionPlan(resultLevel, testType));
            
            result.setIsShared(0); // 默认不分享
            result.setCreateTime(LocalDateTime.now());
            testResultDao.insert(result);
            
            return ResponseResult.ok("测评提交成功").setData(result.getResultId());
        } catch (Exception e) {
            log.error("提交测评失败", e);
            return ResponseResult.error("提交测评失败");
        }
    }

    @Override
    public ResponseResult getTestResult(Long recordId, Long userId) {
        try {
            // 验证记录所有权
            UserTestRecord record = userTestRecordDao.selectById(recordId);
            if (record == null || !record.getUserId().equals(userId)) {
                return ResponseResult.error("测评记录不存在或无权限访问");
            }
            
            if (!"completed".equals(record.getStatus())) {
                return ResponseResult.error("测评尚未完成");
            }
            
            // 获取测评结果
            TestResult result = testResultDao.selectByRecordId(recordId);
            if (result == null) {
                return ResponseResult.error("测评结果不存在");
            }
            
            // 获取答题详情
            List<UserTestAnswer> answers = userTestAnswerDao.selectByRecordId(recordId);
            result.setAnswerDetails(answers);
            
            return ResponseResult.ok("获取成功").setData(result);
        } catch (Exception e) {
            log.error("获取测评结果失败", e);
            return ResponseResult.error("获取测评结果失败");
        }
    }

    @Override
    public ResponseResult getTestHistory(Long userId, Integer page, Integer size) {
        try {
            Page<UserTestRecord> pageObj = new Page<>(page, size);
            IPage<UserTestRecord> result = userTestRecordDao.selectUserTestHistory(pageObj, userId);
            
            // 为每个记录设置进度百分比
            for (UserTestRecord record : result.getRecords()) {
                if (record.getCurrentQuestionIndex() != null) {
                    // 获取总题目数
                    List<TestQuestion> questions = testQuestionDao.selectByTestId(record.getTestId());
                    if (questions.size() > 0) {
                        int progress = (int) Math.round((double) record.getCurrentQuestionIndex() / questions.size() * 100);
                        record.setProgress(Math.min(progress, 100));
                    } else {
                        record.setProgress(0);
                    }
                } else {
                    record.setProgress(0);
                }
            }
            
            return ResponseResult.ok("获取成功").setData(result);
        } catch (Exception e) {
            log.error("获取测评历史失败", e);
            return ResponseResult.error("获取测评历史失败");
        }
    }

    @Override
    public ResponseResult retakeTest(Long testId, Long userId) {
        try {
            // 检查测评是否存在
            PsychologicalTest test = psychologicalTestDao.selectById(testId);
            if (test == null) {
                return ResponseResult.error("测评不存在");
            }
            
            // 创建新的测评记录
            return startTest(testId, userId);
        } catch (Exception e) {
            log.error("重新测评失败", e);
            return ResponseResult.error("重新测评失败");
        }
    }

    /**
     * 分享测评结果
     * @param recordId 测评记录ID
     * @param userId 用户ID
     * @return 分享结果
     */
    @Override
    public ResponseResult shareResult(Long recordId, Long userId) {
        try {
            // 验证记录所有权
            UserTestRecord record = userTestRecordDao.selectById(recordId);
            if (record == null || !record.getUserId().equals(userId)) {
                return ResponseResult.error("测评记录不存在或无权限访问");
            }
            
            if (!"completed".equals(record.getStatus())) {
                return ResponseResult.error("测评尚未完成，无法分享");
            }
            
            // 获取测评基本信息
            PsychologicalTest test = psychologicalTestDao.selectById(record.getTestId());
            if (test == null) {
                return ResponseResult.error("测评信息不存在");
            }
            
            // 生成分享链接
            String shareToken = generateShareToken(recordId, userId);
            String shareUrl = generateShareUrl(shareToken);


            // 生成二维码并上传到OSS
            String qrCodeUrl = generateAndUploadQRCode(shareUrl, test.getTitle(), shareToken);
            
            // 构建分享数据
            Map<String, Object> shareData = new HashMap<>();
            shareData.put("shareUrl", shareUrl);  // 前端分享页面URL
            shareData.put("apiUrl", backendDomain + "/api/test/share/result/" + shareToken);  // 后端API URL
            shareData.put("qrCodeUrl", qrCodeUrl);
            shareData.put("shareToken", shareToken);
            shareData.put("testName", test.getTitle());
            shareData.put("shareText", buildShareText(test.getTitle(), record));
            shareData.put("validDays", 30); // 分享链接有效期30天
            
            log.info("用户 {} 分享测评结果 {}, 分享链接: {}", userId, recordId, shareUrl);
            
            return ResponseResult.ok("生成分享链接成功").setData(shareData);
            
        } catch (Exception e) {
            log.error("分享测评结果失败, recordId: {}, userId: {}", recordId, userId, e);
            return ResponseResult.error("分享失败: " + e.getMessage());
        }
    }
    
    /**
     * 通过分享token获取测评结果
     * @param shareToken 分享token
     * @return 测评结果
     */
    public ResponseResult getSharedResult(String shareToken) {
        try {
            // 解析token获取recordId和userId
            Map<String, Object> tokenData = parseShareToken(shareToken);
            if (tokenData == null) {
                return ResponseResult.error("分享链接无效或已过期");
            }
            
            Long recordId = (Long) tokenData.get("recordId");
            Long userId = (Long) tokenData.get("userId");
            
            // 获取测评记录
            UserTestRecord record = userTestRecordDao.selectById(recordId);
            if (record == null || !record.getUserId().equals(userId)) {
                return ResponseResult.error("测评记录不存在");
            }
            
            if (!"completed".equals(record.getStatus())) {
                return ResponseResult.error("测评尚未完成");
            }
            
            // 获取测评结果
            TestResult result = testResultDao.selectByRecordId(recordId);
            
            if (result == null) {
                return ResponseResult.error("测评结果不存在");
            }
            
            // 获取测评基本信息
            PsychologicalTest test = psychologicalTestDao.selectById(record.getTestId());
            
            // 构建分享结果数据
            Map<String, Object> sharedData = new HashMap<>();
            sharedData.put("testName", test != null ? test.getTitle() : "心理测评");
            sharedData.put("testDescription", test != null ? test.getDescription() : "");
            sharedData.put("completedAt", record.getSubmitTime());
            sharedData.put("totalScore", result.getTotalScore());
            sharedData.put("resultLevel", result.getScoreLevel());
            sharedData.put("resultDescription", result.getScoreDescription());
            sharedData.put("suggestions", result.getSuggestions());
            sharedData.put("shareMode", true); // 标识这是分享模式，前端可据此调整显示
            
            return ResponseResult.ok("获取分享结果成功").setData(sharedData);
            
        } catch (Exception e) {
            log.error("获取分享结果失败, shareToken: {}", shareToken, e);
            return ResponseResult.error("获取分享结果失败");
        }
    }
    
    /**
     * 生成分享token
     * @param recordId 记录ID
     * @param userId 用户ID
     * @return 分享token
     */
    private String generateShareToken(Long recordId, Long userId) {
        // 这里可以使用JWT或者简单的加密方式
        // 为了简单起见，使用Base64编码 + 时间戳
        String data = recordId + ":" + userId + ":" + (System.currentTimeMillis() + 30L * 24 * 60 * 60 * 1000); // 30天过期
        return Base64.getEncoder().encodeToString(data.getBytes());
    }
    
    /**
     * 解析分享token
     * @param shareToken 分享token
     * @return token数据
     */
    private Map<String, Object> parseShareToken(String shareToken) {
        try {
            String data = new String(Base64.getDecoder().decode(shareToken));
            String[] parts = data.split(":");
            if (parts.length != 3) {
                return null;
            }
            
            Long recordId = Long.parseLong(parts[0]);
            Long userId = Long.parseLong(parts[1]);
            Long expireTime = Long.parseLong(parts[2]);
            
            // 检查是否过期
            if (System.currentTimeMillis() > expireTime) {
                return null;
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("recordId", recordId);
            result.put("userId", userId);
            result.put("expireTime", expireTime);
            
            return result;
            
        } catch (Exception e) {
            log.warn("解析分享token失败: {}", shareToken, e);
            return null;
        }
    }
    
    /**
     * 生成分享链接
     * @param shareToken 分享token
     * @return 分享链接
     */
    private String generateShareUrl(String shareToken) {
        // 生成前端分享页面链接，前端页面会调用后端API获取数据
        return appDomain + "/share/" + shareToken;
    }
    
    /**
     * 生成并上传二维码
     * @param shareUrl 分享链接
     * @param testName 测评名称
     * @param shareToken 分享token
     * @return 二维码图片URL
     */
    private String generateAndUploadQRCode(String shareUrl, String testName, String shareToken) {
        try {
            // 生成二维码
            String qrText = "心理测评结果"; // 二维码中央显示的文字
            InputStream qrCodeStream = QRCodeUtil.generateQRCodeWithText(shareUrl, qrText);
            
            // 生成文件名
            String fileName = "result_" + shareToken.substring(0, 8) + "_" + System.currentTimeMillis() + ".png";
            
            // 上传到OSS
            return ossService.uploadQRCode(qrCodeStream, fileName);
            
        } catch (Exception e) {
            log.error("生成并上传二维码失败", e);
            throw new RuntimeException("生成二维码失败", e);
        }
    }
    
    /**
     * 构建分享文本
     * @param testName 测评名称
     * @param record 测评记录
     * @return 分享文本
     */
    private String buildShareText(String testName, UserTestRecord record) {
        return String.format("我刚完成了【%s】心理测评，快来看看我的测评结果吧！ #心理测评 #自我了解", testName);
    }

    @Override
    public ResponseResult getUserTestStats(Long userId) {
        try {
            // 统计用户测评数据
            int totalTests = userTestRecordDao.selectCount(
                new QueryWrapper<UserTestRecord>()
                    .eq("userId", userId)
                    .eq("status", "completed")
            ).intValue();
            
            int testsThisMonth = userTestRecordDao.selectCount(
                new QueryWrapper<UserTestRecord>()
                    .eq("userId", userId)
                    .eq("status", "completed")
                    .ge("submitTime", LocalDateTime.now().withDayOfMonth(1))
            ).intValue();
            
            // 获取最近的测评记录
            List<UserTestRecord> recentTests = userTestRecordDao.selectList(
                new QueryWrapper<UserTestRecord>()
                    .eq("userId", userId)
                    .eq("status", "completed")
                    .orderByDesc("submitTime")
                    .last("LIMIT 5")
            );
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalTests", totalTests);
            stats.put("testsThisMonth", testsThisMonth);
            stats.put("recentTests", recentTests);
            
            return ResponseResult.ok("获取统计数据成功").setData(stats);
        } catch (Exception e) {
            log.error("获取用户测评统计失败", e);
            return ResponseResult.error("获取统计数据失败");
        }
    }



    
    // 私有方法：将字符串状态转换为整数状态
    private Integer convertStatusToInteger(String status) {
        if (status == null) {
            return 0; // 默认未开始
        }
        switch (status) {
            case "new":
                return 0; // 未开始
            case "in_progress":
                return 1; // 进行中
            case "completed":
                return 2; // 已完成
            case "abandoned":
                return 3; // 已放弃
            default:
                return 0; // 默认未开始
        }
    }
    
    // 私有方法：计算标准分
    private BigDecimal calculateStandardScore(int totalScore, String testType) {
        // 根据不同测评类型使用相应的常模数据计算标准分
        double mean = 0; // 均值
        double standardDeviation = 1; // 标准差
        
        switch (testType.toLowerCase()) {
            case "sas":
            case "anxiety":
                // SAS焦虑量表常模数据（修复反向计分后的范围：35-65分）
                mean = 50.0; // 中位数
                standardDeviation = 8.0; // 调整标准差
                break;
            case "sds":
            case "depression":
                // SDS抑郁量表常模数据（示例数据，实际应根据研究数据调整）
                mean = 42.0;
                standardDeviation = 11.0;
                break;
            case "stress":
                // 压力量表常模数据（示例数据，实际应根据研究数据调整）
                mean = 35.0;
                standardDeviation = 8.0;
                break;
            default:
                // 通用测评常模数据
                mean = 50.0;
                standardDeviation = 10.0;
                break;
        }
        
        // 使用TestScoringUtil中的标准T分数计算方法
        double tScore = TestScoringUtil.calculateTScore(totalScore, mean, standardDeviation);
        return BigDecimal.valueOf(Math.round(tScore * 100.0) / 100.0); // 保留2位小数
    }
    
    // 私有方法：生成维度分析
    private String generateDimensions(List<UserTestAnswer> answers, String testType) {
        // 可以根据不同测评类型生成维度分析JSON
        // 这里返回空JSON，实际应用中需要实现具体逻辑
        return "{}";
    }
    
    // 私有方法：生成详细建议
    private String generateDetailedSuggestions(String resultLevel, int totalScore, String testType) {
        // 可以根据结果等级和测评类型生成详细建议JSON
        // 这里返回空JSON，实际应用中需要实现具体逻辑
        return "{}";
    }
    
    // 私有方法：生成行动计划
    private String generateActionPlan(String resultLevel, String testType) {
        // 可以根据结果等级和测评类型生成行动计划JSON
        // 这里返回空JSON，实际应用中需要实现具体逻辑
        return "{}";
    }
    
    // 私有方法：验证并修复JSON格式的suggestions
    private String validateAndFixSuggestions(String suggestions) {
        if (suggestions == null || suggestions.trim().isEmpty()) {
            return "[\"请根据您的具体情况，寻求适当的帮助和支持。\"]";
        }
        
        // 检查是否是"Invalid value."或类似的错误值
        if ("Invalid value.".equals(suggestions) || suggestions.contains("Invalid value")) {
            return "[\"请根据您的具体情况，寻求适当的帮助和支持。\"]";
        }
        
        // 检查是否已经是JSON格式
        String trimmed = suggestions.trim();
        if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
            // 假设已经是JSON数组格式
            return suggestions;
        } else if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
            // 假设已经是JSON对象格式
            return suggestions;
        } else {
            // 将普通字符串转换为JSON数组格式
            return "[\"" + suggestions.replace("\"", "\\\"") + "\"]";
        }
    }
} 